<template>
  <div>
    <el-container>
      <el-header>
        <h2>
          <b>用户管理</b>
        </h2>
      </el-header>
      <el-main>
        <el-form :inline="true" :model="user" ref="user" class="demo-form-inline" align="center">
          <el-form-item label="用户名称" prop="account">
            <el-input v-model="user.account" placeholder="管理员名称"></el-input>
          </el-form-item>
          <el-form-item label="创建时间" prop="regTime">
            <span class="demonstration"></span>
            <el-date-picker
              v-model="user.regTime"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd hh:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="优惠券" prop="discountIds">
            <el-select
              v-model="user.discountIds"
              multiple
              collapse-tags
              style="margin-left: 20px;"
              placeholder="请选择优惠券"
            >
              <el-option
                :label="discount.name"
                :value="discount.id"
                v-for="(discount,index) in discounts"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="user.status" placeholder="请选择状态">
              <el-option label="全部" value="0"></el-option>
              <el-option label="正常" value="1"></el-option>
              <el-option label="冻结" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="page=1;onSubmit()">查询</el-button>
            <el-button @click="resetForm('user')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="tData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column prop="account" label="账号" width="168"></el-table-column>
          <el-table-column prop="phoneNum" label="电话号码" width="168"></el-table-column>
          <el-table-column prop="regTime" label="注册时间" width="168"></el-table-column>
          <el-table-column prop="score" label="积分" width="168"></el-table-column>
          <el-table-column prop="status" label="状态" width="168" :formatter="formatStatus"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="view(scope.row)" type="primary" size="mini">查看</el-button>
              <el-button @click="handleClick(scope.row)" type="primary" size="mini">分配优惠券</el-button>
              <el-button
                @click="changeStatus(scope.row)"
                type="danger"
                size="mini"
                v-if="scope.row.status==1"
              >冻结</el-button>
              <el-button
                @click="changeStatus(scope.row)"
                type="success"
                size="mini"
                v-if="scope.row.status==2"
              >解冻</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalNum"
          :page-size="3"
          align="center"
          :current-page="page"
          @current-change="handleCurrentChange"
        ></el-pagination>
        <br />
        <div align="center">
          <el-button type="danger" @click="delAll">批量冻结</el-button>
          <el-button type="success" @click="unDelAll">批量解冻</el-button>
        </div>
      </el-main>
    </el-container>

    <el-dialog
      title="分配优惠券"
      :visible.sync="dialogFormVisibleDis"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form
        :inline="true"
        :model="disForm"
        ref="disForm"
        class="demo-form-inline"
        align="center"
        :rules="formrules"
      >
        <el-form-item label="优惠券" prop="discountId">
          <el-select v-model="disForm.discountId" style="margin-left: 20px;" placeholder="请选择优惠券">
            <el-option
              :label="discount.name"
              :value="discount.id"
              v-for="(discount,index) in discounts"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input v-model.number="disForm.num " placeholder="请输入数量"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="onClose('disForm')">取 消</el-button>
          <el-button type="primary" @click="addDis('disForm')">确 认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="优惠券信息"
      :visible.sync="dialogFormVisibleView"
      :modal="false"
      :close-on-click-modal="false"
    >
      <el-table :data="userDis" border style="width: 100%">
        <el-table-column prop="name" label="优惠券名"></el-table-column>
        <el-table-column prop="expiryDate" label="有效期"></el-table-column>
        <el-table-column prop="time" label="截止时间"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import Axios from "axios";
import Qs from "qs";
export default {
  data() {
    var validateNum = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("不能为负数或0"));
      } else {
        callback();
      }
    };
    return {
      user: {
        account: "",
        discountId: "",
        regTime: "",
        status: "",
      },
      disForm: {
        id: "",
        discountIds: "",
        num: "",
      },
      formrules: {
        discountId: [
          { required: true, message: "请选择优惠券", trigger: "change" },
        ],
        num: [
          { required: true, message: "请输入数量", trigger: "blur" },
          { type: "number", message: "数量必须为数字值" },
          { validator: validateNum, trigger: "blur" },
        ],
      },
      discounts: [],
      userDis: [],
      tData: [],
      multipleSelection: [],
      totalNum: 0,
      page: 1,
      dialogFormVisibleDis: false,
      dialogFormVisibleView: false,
      formLabelWidth: "120px",
    };
  },
  created() {
    Axios.get("/tfss/admin/discount/list").then((r) => {
      if (r.data.code == 200) {
        this.discounts = r.data.data;
        this.onSubmit();
      } else if (r.data.code == 403) {
        this.$message.error("没有权限");
      } else if (r.data.code == 703) {
        this.$message.error("未登录");
      } else if (r.data.code == 500) {
        this.$message.error("系统繁忙，请稍后再试");
      } else if (r.data.code == 704) {
        this.$message.error("登录失效，请重新登录");
      }
    });
  },
  methods: {
    onSubmit() {
      Axios.get("/tfss/admin/user/listByPage", {
        params: {
          account: this.user.account,
          discountIds: this.user.discountIds,
          regTime: this.user.regTime,
          status: this.user.status,
          page: this.page,
        },
        paramsSerializer: (params) => {
          return Qs.stringify(params, { indices: false });
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.tData = r.data.data.records;
          this.totalNum = r.data.data.total;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addDis(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确认增加?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              Axios.post(
                "/tfss/admin/user/addDis",
                Qs.stringify(this.disForm, { indices: false })
              ).then((r) => {
                if (r.data.code === 200) {
                  this.$message({
                    type: "success",
                    message: "增加成功!",
                  });
                  this.$refs[formName].resetFields();
                  this.dialogFormVisibleDis = false;
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                } else if (r.data.code == 706) {
                  this.$message.error("角色名已存在");
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          return false;
        }
      });
    },
    onClose(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisibleDis = false;
      this.dialogFormVisibleView = false;
    },
    view(row) {
      this.userDis = [];
      Axios.get("/tfss/admin/user/view", {
        params: {
          id: row.id,
        },
      }).then((r) => {
        if (r.data.code == 200) {
          let results = r.data.data;
          for (const result of results) {
            let dis = {
              name: "",
              expiryDate: "",
              time: "",
            };
            for (const discount of this.discounts) {
              if (result.discountId == discount.id) {
                dis.name = discount.name;
                dis.expiryDate = discount.expiryDate;
                dis.time = result.time;
                this.userDis.push(dis);
                break;
              }
            }
          }
          this.dialogFormVisibleView = true;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
    handleClick(row) {
      this.dialogFormVisibleDis = true;
      this.disForm.id = row.id;
    },
    changeStatus(row) {
      this.$confirm("确认继续操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          Axios.get("/tfss/admin/user/changeStatus", {
            params: {
              id: row.id,
            },
          }).then((r) => {
            if (r.data.code == 200) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.onSubmit();
            } else if (r.data.code == 403) {
              this.$message.error("没有权限");
            } else if (r.data.code == 703) {
              this.$message.error("未登录");
            } else if (r.data.code == 500) {
              this.$message.error("系统繁忙，请稍后再试");
            } else if (r.data.code == 704) {
              this.$message.error("登录失效，请重新登录");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    delAll() {
      this.$confirm("此操作将冻结所有已选择用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (const row of this.multipleSelection) {
            if (row.status == "1") {
              Axios.get("/tfss/admin/user/changeStatus", {
                params: {
                  id: row.id,
                },
              }).then((r) => {
                if (r.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: row.account + "冻结成功!",
                  });
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                }
              });
            } else {
              this.$message.warning(row.account + "已为冻结状态");
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    unDelAll() {
      this.$confirm("此操作将解冻所有已选择用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (const row of this.multipleSelection) {
            if (row.status == "2") {
              Axios.get("/tfss/admin/user/changeStatus", {
                params: {
                  id: row.id,
                },
              }).then((r) => {
                if (r.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: row.account + "解冻成功!",
                  });
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                }
              });
            } else {
              this.$message.warning(row.account + "已为正常状态");
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    formatStatus(row, column, cellValue) {
      if (cellValue == "1") {
        return "正常";
      } else if (cellValue == "2") {
        return "冻结";
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      Axios.get("/tfss/admin/user/listByPage", {
        params: {
          account: this.user.account,
          discountIds: this.user.discountIds,
          regTime: this.user.regTime,
          status: this.user.status,
          page: val,
        },
        paramsSerializer: (params) => {
          return Qs.stringify(params, { indices: false });
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.tData = r.data.data.records;
          this.totalNum = r.data.data.total;
          this.page = val;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
  },
};
</script>

<style scoped>
.el-header,
.el-footer {
  /* background-color: #b3c0d1; */
  color: #333;
  /* text-align: center; */
  line-height: 60px;
}
.el-main {
  /* background-color: #e9eef3; */
  color: #333;
  /* text-align: center; */
  /* line-height: 160px; */
}
</style>